//
//  OtherCostCommitVC.m
//  KuWoCan
//
//  Created by hwd on 17/4/12.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "OtherCostCommitVC.h"

#import "LabTextFieldCell.h"
#import "NWSaleApplyRequest.h"
#import "PhotoManageCell.h"
#import "LabTxtViewCell.h"
#import "PicPageListModel.h"

#define kOCParaDicKey_title @"title"
#define kOCParaDicKey_explains @"explains"
#define kOCParaDicKey_costs @"costs"

#define kOCParaDicKey_photoList @"photoList"

@interface OtherCostCommitVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tabView;

@property (nonatomic,strong) NSMutableDictionary *paraDic;

@property (nonatomic,strong) NSMutableArray *paraDataArr;

@property (nonatomic,copy) NSArray *keysArr;

@property (nonatomic,copy) NSArray *leftStrArr;

@property (nonatomic,copy) NSMutableArray *picArrFirst;


@end

@implementation OtherCostCommitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.moduleType == HomeModuleTypeOA) {
        self.title = @"其他费用申请";
    } else {
        self.title = @"其他费用核销";
    }
    _leftStrArr = @[@"主旨",@"内容及形式",@"费用总计"];
    _picArrFirst = [[NSMutableArray alloc]init];
    _picHXArr = [[NSMutableArray alloc]init];
    _keysArr = @[kOCParaDicKey_title,kOCParaDicKey_explains,kOCParaDicKey_costs];
    [self paraDataArr];
    [self paraDic];
    if (_isChangeInfo)
    {
        [self prepareDataForChangeOrder];
        [self getPicData];
       
    }else
    {
        [_paraDic setValue:@""  forKey:kOCParaDicKey_title];
        [_paraDic setValue:@"" forKey:kOCParaDicKey_explains];
        [_paraDic setValue:@"" forKey:kOCParaDicKey_costs];
    }
    
    [self setUpUI];
}
-(void)getPicData//获取上传的图片
{
    [_picArr removeAllObjects];
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestQueryPicWithProcessId:[ToolViewViewController isNotNullStr:_orderId]?_orderId:@"" pageNo:@"1" pageSize:@"10" type:[NSString stringWithFormat:@"%zd", _moduleType == HomeModuleTypeOA?PicTypeOtherFeeAdd:12]];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
            if ([pageModel.count integerValue] > 0)
            {
                self.picArr = pageModel.list.mutableCopy;
            }
            
        }
        [self getHXPicData];
    }];
}
-(void)getHXPicData//获取核销的图片
{
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestQueryPicWithProcessId:[ToolViewViewController isNotNullStr:_orderId]?_orderId:@"" pageNo:@"1" pageSize:@"10" type:[NSString stringWithFormat:@"%zd",10]];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
            if ([pageModel.count integerValue] > 0)
            {
                self.picHXArr = pageModel.list.mutableCopy;
            }
            
        }
        [_tabView reloadData];
    }];

}
- (void)prepareDataForChangeOrder  //修改订单进入后 显示传来的数据
{
    [_paraDic setValue:_detailInfoModel.title  forKey:kOCParaDicKey_title];
    [_paraDic setValue:_detailInfoModel.explains forKey:kOCParaDicKey_explains];
    [_paraDic setValue:_detailInfoModel.costs forKey:kOCParaDicKey_costs];
    
    
    if (_moduleType == HomeModuleTypeOC)
    {
        //图片参数处理
        NSMutableArray *picParaArr = [NSMutableArray array];
        _picArr = [NSMutableArray arrayWithArray:_detailInfoModel.photoList];
        if (_picArr && _picArr.count > 0)
        {
            for (PicListModel *model in _picArr)
            {
                [picParaArr addObject:@{@"type":model.type,@"title":model.title,@"imgs":model.imgs}];
            }
        }
        NSString *picParaStr = [CommonTool beJsonStrWithObj:picParaArr];
        [_paraDic setValue:picParaStr forKey:kOCParaDicKey_photoList];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSMutableArray *)paraDataArr
{
    if (!_paraDataArr)
    {
        _paraDataArr = [NSMutableArray array];
    }
    return _paraDataArr;
}

- (NSMutableDictionary *)paraDic
{
    if (!_paraDic)
    {
        _paraDic = [NSMutableDictionary dictionary];
    }
    return _paraDic;
}

- (void)setUpUI
{
    //创建列表
    _tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _tabView.backgroundColor = KwBgColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];
    
    //创建底部按钮
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(startPlaceAnOrder) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
   
   
    
}

//提交申请
- (void)startPlaceAnOrder
{
    
    for (NSString *key in [_paraDic allKeys]) {
        if ([_paraDic[key] isEqual:@""] || [_paraDic[key] isEqual:[NSNull class]]) {
            [_paraDic removeObjectForKey:key];
        }
    }
    if (!_paraDic[kOCParaDicKey_title] || ![ToolViewViewController isNotNullStr:_paraDic[kOCParaDicKey_title]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加主旨"];
        return;
    }
    if (!_paraDic[kOCParaDicKey_explains] || ![ToolViewViewController isNotNullStr:_paraDic[kOCParaDicKey_explains]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加内容及形式"];
        return;
    }
    if (!_paraDic[kOCParaDicKey_costs] || ![ToolViewViewController isNotNullStr:_paraDic[kOCParaDicKey_costs]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加费用总计"];
        return;
    }


    if ([_paraDic allKeys].count >= 3)
    {
        [_paraDic setValue:@"0" forKey:@"approvalType"];
        [_paraDic setValue:[Singleton shareInstance].userId forKey:@"user.id"];
        if (_isChangeInfo)
        {
            [_paraDic setValue:_orderId forKey:@"id"];
            if (_moduleType == HomeModuleTypeOA)
            {
                [_paraDic setValue:@"1" forKey:@"approvalStatus"];
            }
            else
            {
                [_paraDic setValue:_orderStatus forKey:@"examineStatus"];
            }
        }
        else
        {
            [_paraDic setValue:@"1" forKey:@"approvalStatus"];
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请完善信息"];
        return;
    }
  
    if (_picArrFirst.count>0) {
         [_paraDic setValue:[CommonTool beJsonStrWithObj:_picArrFirst] forKey:@"otherAPhotoList"];
    }
    
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            if (_moduleType == HomeModuleTypeOC) {
                if (self.reloadBlock) {
                    self.reloadBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
    
    if (!_isChangeInfo)
    {
        [request startRequestCommitOtherApplyWithDic:_paraDic];
    }
    else
    {
        if (_moduleType == HomeModuleTypeOC)
        {
            [_paraDic removeObjectForKey:@"photoList"];
            [request startRequestUpdateOtherCheckWithDic:_paraDic];
        }
        else
        {
            [request startRequestUpdateOtherApplyWithDic:_paraDic];
        }
    }
}

#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_moduleType == HomeModuleTypeOC)
    {
        return 3;
    }
    else
    {
        return 2;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return _leftStrArr.count;
    }
    else
    {
        if (_moduleType == HomeModuleTypeOA)
        {
            return 1;
        }
        else
        {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *photoManageCell_ID = @"PhotoManageCell";
    static NSString *labTxtViewCell_ID = @"LabTextFieldCell";
    
    //活动名称
    if (indexPath.section == 0)
    {
        if (indexPath.row == 1)
        {
            LabTxtViewCell *cell = [tableView dequeueReusableCellWithIdentifier:labTxtViewCell_ID];
            if (!cell)
            {
                cell = [[LabTxtViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:labTxtViewCell_ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSString *keyStr = _keysArr[indexPath.row];
            cell.txtStr = [_paraDic objectForKey:keyStr];
            cell.topLab.text = _leftStrArr[indexPath.row];
            cell.block = ^(NSString *str){
                [_paraDic setObject:str forKey:keyStr];
            };
            return cell;
        }
        else
        {
            NSString *labTextFieldCell_ID = [NSString stringWithFormat:@"LabTextFieldCell%ld%ld",indexPath.section,indexPath.row];
            LabTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:labTextFieldCell_ID];
            if (!cell)
            {
                cell = [[LabTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:labTextFieldCell_ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.constStr = _leftStrArr[indexPath.row];
            NSString *keyStr = _keysArr[indexPath.row];
//            cell.rightTxtF.text = [NSString stringWithFormat:@"%@",[_paraDic objectForKey:keyStr]];
            cell.paraStr = [NSString stringWithFormat:@"%@",[_paraDic objectForKey:keyStr]];
            cell.block = ^(NSString *str){
                [_paraDic setObject:str forKey:keyStr];
            };
            return cell;
        }
        
    }
    else
    {
        PhotoManageCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:photoManageCell_ID];
        if (!cell)
        {
            cell = [[PhotoManageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:photoManageCell_ID];
            
        }
        cell.vc = self;
        cell.orderId = _orderId;
        cell.isChange = _isChangeInfo;
        cell.isSubmit = _isSubmit;
        
        if (indexPath.section == 1) {
            cell.titleLabel.text = @"照片管理";
            cell.picType = _moduleType == HomeModuleTypeOA?PicTypeOtherFeeAdd:12;
            [cell configCell:_picArr];
            cell.choosePictureHandle = ^(NSArray<PicListModel *> *PicArr) {
                [_picArr removeAllObjects];
                for (PicListModel *model in PicArr.mutableCopy)
                {
                    [_picArr addObject:model];
//                    增加2个类型（type）
//                    11其他费用申请      说明照片
//                    12其他费用核销      说明照片
                    [PicArr enumerateObjectsUsingBlock:^(PicListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [_picArrFirst addObject:@{@"type":_moduleType == HomeModuleTypeOA?@"11":@"12", @"title": obj.title, @"imgs": obj.imgs}];
                    }];
                }
            };
        }else{
            cell.titleLabel.text = @"票据照片管理";
            cell.picType = PicTypeOtherFeeCheck;
            [cell configCell:_picHXArr];
            cell.choosePictureHandle = ^(NSArray<PicListModel *> *PicArr) {
        
                [_picHXArr removeAllObjects];
                for (PicListModel *model in PicArr.mutableCopy)
                {
                    [_picHXArr addObject:model];
                    [_picArrFirst addObject:@{@"type":_moduleType == HomeModuleTypeOA?@"11":@"12",@"title":model.title,@"imgs":model.imgs}];
                }
            };
        }
        return cell;
    }
}

@end



